<template>
	<div class="calendar-container"> <!-- 新增一个更具语义的外层容器类名 -->
		
		<!-- 制作日历 -->
		<ul class="calendar-header">
			<li>一</li>
			<li>二</li>
			<li>三</li>
			<li>四</li>
			<li>五</li>
			<li>六</li>
			<li>日</li>
		</ul>
		<!-- 日历身体 -->
		<ul class="calendar-body"> <!-- 类名调整为更具语义的形式 -->
			<li v-for="(item, index) in newArray" :key="index" :class="isCurrentMonth(item)? '' : 'masking'"
				@click="clickTime(item)">
				<!-- 日期 -->
				<div class="date-info">
					<p>{{ item.date }}</p>
					<img v-if="item.state == '休'"
						src="https://mp-7f09bcd1-475b-4778-8767-52ae180f55ab.cdn.bspapp.com/cloudstorage/休息日.svg"
						alt="休息标识" style="width: 14px;height: 14px;" />
				</div>
				<div class="tag" v-if="isCurrentMonth(item)">
					<van-tag type="success" v-if="item.workingHours && item.workingHours!= 0">
						正:{{ item.workingHours }}h
					</van-tag>

					<van-tag color="#A6E22B" v-if="
                          item.workingHours &&
                          item.workingHours == 0 &&
                          item.leave &&
                          item.leave == 0 &&
                          item.overtime &&
                          item.overtime == 0
                        ">
						放假
					</van-tag>

					<van-tag color="#494949" v-if="item.leave && item.leave!= 0">
						调:{{ item.leave }}h
					</van-tag>

					<van-tag type="warning" v-if="item.overtime && item.overtime!= 0">加:{{ item.overtime }}h</van-tag>
				</div>
			</li>
		</ul>

		<van-empty v-if="dataList.length == 0" description="空空如也" style="
				position: absolute;
				top: 50%;
				left: 0;
				width: 100%;
				transform: translateY(-50%);
			" />

		<!-- 日期选择器 -->

		<div class="header-top"> <!-- 类名调整为更规范的格式 -->
			<button @click="statisticsShow = true">统计面板</button>
			<div class="time">
				<button @click="cutTime(1)">上一月</button>
				<p @click="selectTimeShow = true">{{ createTime }}</p>
				<button @click="cutTime(2)">下一月</button>
			</div>
		</div>
		
		<div class="btn"> 
			<button @click="add">添加考勤</button>
		</div>

		<van-popup :show="selectTimeShow" position="bottom" @close="selectTimeShow = false">
			<van-datetime-picker type="year-month" :value="currentDate" :min-date="minDate" @confirm="onInput"
				@cancel="selectTimeShow = false" />
		</van-popup>

		<van-popup :show="statisticsShow" position="center" @close="statisticsShow = false" round>
			<div class="lookInfo">
				<div class="userInfo">
					<p><span>用户名称</span>：{{ userName }}</p>
					<p><span>出勤统计</span>：{{ `${beOnDuty}小时 【共】 ${beOnDuty / 8}天` }}</p>
					<p><span>加班统计</span>：{{ `${jiaBeOnDuty}小时【共】 ${jiaBeOnDuty / 8}天` }}</p>
					<p><span>请假统计</span>：{{ `${qingBeOnDuty}小时【共】${qingBeOnDuty / 8}天` }}</p>
				</div>
				<button @click="uploadFile">导出考勤表格</button>
			</div>
		</van-popup>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				dataList: [],

				createTime: "",

				newArray: [],

				userInfo: uni.getStorageSync("userInfo"),

				// 上班总时长
				beOnDuty: 0,
				// 加班总时长
				jiaBeOnDuty: 0,
				// 请假
				qingBeOnDuty: 0,

				selectTimeShow: false,

				userName: "",

				currentDate: new Date().getTime(),

				minDate: new Date("2023-01").getTime(),


				statisticsShow: false
			};
		},

		onShow() {
			if (!this.createTime) {
				this.createTime = this.$getTime('yyyy-MM')
			}

			this.getInit();
		},

		onLoad() {
			this.userName = this.userInfo.userName;
		},

		methods: {
			// 获取数据
			getInit() {
				this.beOnDuty = 0;
				this.jiaBeOnDuty = 0;
				this.qingBeOnDuty = 0;

				this.$axios("overallSituation", {
					databaseName: "checkOnWorkAttendance",
					state: "look",
					createTime: this.createTime,
					userName: this.userName,
				}, true).then((res) => {
					if (res.code == 200) {
						res.data.forEach((item, index) => {
							this.beOnDuty += Number(item.workingHours);
							this.jiaBeOnDuty += Number(item.overtime);
							this.qingBeOnDuty = Number(this.qingBeOnDuty) + Number(item.leave);
						});
						this.dataList = res.data;

						if (this.dataList.length == 0) {
							this.dataList.push({
								"date": "01",
								"createTime": this.createTime + "-01",
								"userName": "何俊东"
							})
						}

						this.newArray = [];
						// 将数据从后往前排序
						this.dataList.forEach((item) => {
							this.newArray.unshift(item);
						});

						this.disposeDate(); //处理数据
					}
				});
			},

			// 处理数据
			async disposeDate() {
				// 判断第一个数据 是周几
				let date = new Date(this.newArray[0].createTime);
				let newDay = date.getDay() == 0 ? 6 : date.getDay() - 1;

				let supplement = newDay; //得到要在日历之前补充的数值

				for (let i = 0; i < supplement; i++) {
					let fill = this.getYesterday(date, i + 1, "before");

					this.newArray.unshift({
						...fill,
					});
				}

				// 一个日历应该显示 42 个 格子  判断当前长度 补充不够的格子
				if (this.newArray.length < 42) {
					let number = 42 - this.newArray.length - 1;
					let endDate = new Date(
						this.newArray[this.newArray.length - 1].createTime
					); //获取数据中最后一个日期

					for (let i = 0; i <= number; i++) {
						let fill = this.getYesterday(endDate, i + 1, "later");
						this.newArray.push({
							...fill,
						});
					}
				}

				let result_date = await this.$axios('overallSituation', {
					databaseName: "festival_date",
					state: "look"
				})

				let special_date_rest = []
				let special_date_work = []
				result_date.data.forEach(item => {
					if (item.type == '休') {
						special_date_rest.push(item.time)
					} else if (item.type == '班') {
						special_date_work.push(item.time)
					}
				})

				// 判断每一个格子 是否休息 或者上班
				this.newArray.forEach(item => {
					// 判断当前日期 是不是存在两个集合中
					if (special_date_rest.includes(item.createTime)) {
						this.$set(item, 'state', '休')
					} else if (special_date_work.includes(item.createTime)) {
						this.$set(item, 'state', '')
					} else {
						let date = new Date(item.createTime).getDay()
						if (date == 0 || date == 6) {
							this.$set(item, 'state', '休')
						} else {
							this.$set(item, 'state', '')
						}
					}
				})

			},

			// 点击上一个月 或者 下一个月
			cutTime(type) {
				let currentDate = new Date(this.createTime);
				let currentYear = currentDate.getFullYear();
				let currentMonth;
				if (type == 1) {
					currentMonth = currentDate.setMonth(currentDate.getMonth() - 1);
				} else {
					currentMonth = currentDate.setMonth(currentDate.getMonth() + 1);
				}

				this.createTime = this.$getTime('yyyy-MM', currentMonth)
				this.getInit()
			},

			clickTime(item) {
				if (!this.isCurrentMonth(item)) {
					this.createTime = this.$getTime('yyyy-MM', item.createTime)
					this.getInit()
				}
			},
			
			add(){
				uni.navigateTo({
					url: "/subPackages/pages/checkOnWorkAttendance/addList",
				});
			},
			
			// 选择时间
			onInput(event) {
				this.createTime = this.$getTime('yyyy-MM', event.detail);
				this.getInit();
				this.selectTimeShow = false;
			},

			// 点击下载附件
			async uploadFile(e) {
				let result = await this.$axios('getExcelInfo', {
					data: this.dataList
				}, true)
				
				let downloadFile = uni.downloadFile({
					url: result.fileID,
					success: (res) => {
						uni.showLoading({
							title:"正在打开文件"
						})
						// 打开文件
						uni.openDocument({
							filePath: res.tempFilePath,
							showMenu: true, //允许分享
						});
						uni.hideLoading();
					},
				});
			},

			getYesterday(time, number, frontAndBack) {
				let today = new Date(time); // 获取当前日期

				if (frontAndBack == "before") {
					today.setDate(today.getDate() - number); // 设置为前 n 天
				} else {
					today.setDate(today.getDate() + number); // 设置为后 n 天
				}

				// 格式化日期为 YYYY-MM-DD
				let year = today.getFullYear();
				let month =
					today.getMonth() + 1 < 10 ?
					"0" + (today.getMonth() + 1) :
					today.getMonth() + 1; // 月份从0开始，所以加1
				let date = today.getDate() < 10 ? "0" + today.getDate() : today.getDate();
				return {
					year,
					month,
					date,
					createTime: `${year}-${month}-${date}`,
				};
			},

			// 判断当前日期是不是当前月
			isCurrentMonth(item) {
				let currentMonth = new Date(this.createTime).getMonth() + 1;
				let timeMonth = new Date(item.createTime).getMonth() + 1;
				if (currentMonth == timeMonth) {
					return true;
				} else {
					return false;
				}
			},
		},
	};
</script>

<style scoped>
	/* 整体日历容器样式 */
	.calendar-container {
		width: 100%;
		min-height: 100vh;
		background-color: #f4f4f4;
		/* 整体背景色改为更淡雅的灰色调 */
		font-family: Arial, sans-serif;
		/* 设置统一的字体，增强整体感 */
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	/* 顶部标题栏样式 */
	.header-top {
		width: 100%;
		height: 60px;
		box-sizing: border-box;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.header-top p {
		font-size: 12px;
		color: #333;
		margin: 0 10px;
	}

	.header-top button,
	.header-top .time {
		font-size: 12px;
		border: 1px solid #f1f1f1;
		margin: 10px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.expand-btn {
		color: #007bff;
		/* 展开全部按钮设置为主题色，更醒目 */
		cursor: pointer;
	}

	/* 日历头部（星期几）样式 */
	.calendar-header {
		width: 100%;
		height: 50px;
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: #fff;
		border-bottom: 1px solid #ccc;
	}

	.calendar-header li {
		width: 14.28%;
		text-align: center;
		font-size: 14px;
		font-weight: normal;
		/* 去除加粗，更简洁 */
		color: #666;
	}

	/* 日历主体样式 */
	.calendar-body {
		width: 100%;
		max-height: 83vh;
		/* 限制最大高度，避免过长 */
		overflow-y: auto;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
		background-color: #fff;
	}

	.calendar-body li {
		width: 14.28%;
		height: 90px;
		box-sizing: border-box;
		border: 1px solid #eee;
		/* 简化边框样式 */
		padding: 8px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
	}

	.calendar-body li .date-info {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
	}

	.calendar-body li .date-info p {
		font-size: 12px;
		font-weight: bold;
		color: #333;
	}

	.calendar-body li .date-info img {
		position: absolute;
		top: 0;
		right: 0;
	}

	.calendar-body li .tag {
		font-size: 12px;
		width: 100%;
	}

	.lookInfo {
		width: 80vw;
		text-align: left;
		padding: 10px;
		box-sizing: border-box;
		background: #fff;
	}

	.lookInfo p {
		font-size: 12px;
		margin: 5px 0;
	}

	.lookInfo button {
		width: 97%;
		height: 35px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		background: #ef5350;
		font-size: 12px;
		font-weight: 700;
		margin: 0 auto;
		margin-top: 10px;
	}

	.lookInfo .userInfo {
		width: 100%;
		padding: 10px;
		box-sizing: border-box;
		border: 1px solid #ef5350;
		border-left: 5px solid #ef5350;
		border-right: 5px solid #ef5350;
		border-radius: 10px;
	}

	.lookInfo .userInfo p span {
		font-weight: 700;
	}

	.masking {
		background-color: #f8f9fa;
		/* 非当前月日期的背景色调整 */
		color: #999;
	}

	/* 弹出框通用样式（可根据实际情况进一步细化调整各弹出框差异样式） */
	.van-popup {
		border-radius: 8px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
		background-color: #fff;
	}
	
	.btn {
		padding: 10px;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		left: 0;
		bottom: 10px;
		width: 100%;
		height: 50px;
	}
	
	.btn button {
		width: 97%;
		height: 35px;
		background-color: #7950f2;
		border-bottom: none;
		font-size: 12px;
		color: #fff;
		font-weight: 700;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 10px;
	}
</style>